import { View, Text, Image } from '@tarojs/components'
import CloudIcons from '@/assets/ImageUrlConfig.js'
import { useState } from 'react'
import './index.scss'
import { useSelector, useDispatch } from 'react-redux'
import { navigateTo, cloud, showToast } from '@tarojs/taro'
import { GetArticleApi } from '@/api/index'

export default function ArticleList({ showArticleOperationDrawer, backToHomeDefault }) {
	const dispatch = useDispatch()

	const spaceStore = useSelector((state) => state.space)
	const recentStore = useSelector((state) => state.recent)

	const [isShowOperationDrawer, setIsShowOperationDrawer] = useState(false)

	const dispalyArticle = (article) => {
		const recent = { ...recentStore }
		if (recent[spaceStore._id]) {
			if (recent[spaceStore._id].children.findIndex((item) => item._id === article._id) === -1) {
				recent[spaceStore._id].children.push(article)
			}
		} else {
			recent[spaceStore._id] = {
				_id: spaceStore._id,
				name: spaceStore.name,
				children: [article],
			}
		}
		dispatch({
			type: 'UPDATE_RECENT',
			payload: recent,
		})
		GetArticleApi({ id: article._id })
			.then((data) => {
				dispatch({
					type: 'UPDATE_ARTICLE',
					payload: data,
				})
				backToHomeDefault()
			})
			.catch(() => {
				showToast({
					title: '读取失败',
					icon: 'error',
					duration: 1000,
				})
			})
	}
	return (
		<View className='article-container'>
			<View className='article-list'>
				{spaceStore?.article?.map((article) => {
					return (
						<View
							className='article-item'
							onTap={() => {
								dispalyArticle(article)
							}}
						>
							<Text className='article-name'>{article.title}</Text>
							<View className='article-operation'>
								<Image
									className='img'
									onTap={(e) => {
										e.stopPropagation()
										showArticleOperationDrawer(article._id)
									}}
									src={CloudIcons.more}
								></Image>
							</View>
						</View>
					)
				})}
			</View>
		</View>
	)
}
